/****************************************************
          File Name:test_i.cpp
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Thu 25 Dec 2014 09:21:04 PM CST
*****************************************************/

#include"test.h"
#include<cstring>

using std::strlen;
using std::strcpy;
using std::strcat;
using std::cout;
using std::ostream;

String::String(const char *s)
{
    str = new char[strlen(s) + 1];
    strcpy(str, s);
}

String::String()
{
    str = new char[1];
    str[0] = '\0';
}

String::String(const String &s)
{
    str = new char[strlen(s.str) + 1];
    strcpy(str, s.str);
}

String::~String()
{
    cout << std::endl;
    cout << str << " --> deleted\n";
    delete [] str;
}

ostream & operator<<(ostream & os, const String & s)
{
    os << s.str;

    return os;
}

String & String::operator=(const String & s)
{
    if(this == &s)
        return *this;
    delete [] str;
    int len = strlen(s.str);
    str = new char[len + 1];
    strcpy(str, s.str);
    return *this;
}
/*
exsit or not, make no defference !!!!
String  String::operator+(const char *s)
{
    int len, ls, lstr;
    ls = strlen(s);
    lstr = strlen(str);
    len = ls + lstr;

    char *tmp = new char[lstr];
    strcpy(tmp, str);               // backup old str

    delete [] str;

    str = new char[len + 1];
    strncpy(str, tmp, lstr);
    strcat(str, s);

    delete tmp;                 // delete temperary value

    return *this;
}
*/
String  String::operator+(const String & s)
{
    String res;
    int len;
    len = strlen(s.str) + strlen(str);                // total len

    res.str = new char[len + 1];
    strcpy(res.str, str);
    strcat(res.str, s.str);

    return res;
}

String  operator+(const char *s1, const String & s2)
{
    String tmp;

    tmp.str = new char[strlen(s1) + strlen(s2.str) + 1];
    strcpy(tmp.str, s1);
    strcat(tmp.str, s2.str);

    return tmp;
}
